package com.dao;
import com.entity.reader;
import com.utils.PropertiesUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class readerDao {
    public void add(reader userlogin) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "insert into readerlogin(nickname,password,email,sex,phone) values(?,?,?,?,?)";
        queryRunner.update(sql,userlogin.getNickname(),userlogin.getPassword(),userlogin.getEmail(),userlogin.getSex(),userlogin.getPhone());
    }
//    public void delete(String userlogin) throws SQLException{
//        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
//        String sql = "delete from userlogin where username = ?";
//        queryRunner.update(sql,userlogin);
//    }
//    public void updata(user userlogin) throws  SQLException{
//        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
//        String sql = "update userlogin set username = ?, password = ?";
//        queryRunner.update(sql,userlogin.getUser(),userlogin.getPassword());
//    }
    public List<reader> list(reader userlogin) throws  SQLException{
        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from readerlogin";
        List<reader> list = queryRunner.query(sql, new BeanListHandler<>(reader.class));
        return list;
    }
    public reader findByPhone(String phone) throws SQLException{
        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from readerlogin where phone = ?";
        reader user = queryRunner.query(sql, new BeanHandler<>(reader.class),phone);
        return user;
    }

    public reader findByEmail(String email) throws SQLException{
        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from readerlogin where  email = ?";
        reader user = queryRunner.query(sql, new BeanHandler<>(reader.class),email);
        return user;
    }

    public reader login(reader userman) throws  SQLException{
        QueryRunner queryRunner = new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from readerlogin where ((phone = ? and password = ?) or (email = ? and password = ?))";
        reader entity = queryRunner.query(sql, new BeanHandler<>(reader.class), userman.getPhone(), userman.getPassword(),userman.getEmail(), userman.getPassword());
        return entity;
    }
}
